package com.yuanye.gwcit;

import android.Manifest;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;

import com.elvishew.xlog.XLog;
//import com.hjq.permissions.OnPermissionCallback;
//import com.hjq.permissions.XXPermissions;
import com.yuanye.yeecho.utils.BlueToothController;
import com.yuanye.gwcit.utils.GT;
import com.yuanye.yeecho.base.BaseActivity;
import com.yuanye.yeecho.callback.CommonCallback;
import com.yuanye.yeecho.utils.WifiUtil;

import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

public class MainActivity extends BaseActivity {
    private static final String TAG = MainActivity.class.getSimpleName();

    boolean IS_PERMISSION_GRANTED = false;
    boolean IS_WIFI_CONNECTED = false;
    boolean IS_BLUETOOTH_OPEN = false;
    boolean IS_CAN_LOGIN = false;
    boolean IS_CONFIG_LOADED = false;

    private Handler handler;
    private EditText etFixture, etUsername, etPassword;
    private ScrollView scrollView;
    private TextView textView;

    final String WIFI_NAME = "gwtest";
    final String WIFI_PSWD = "gwtest123";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);        ActionBar actionBar = getSupportActionBar();
        actionBar.setHomeButtonEnabled(true);
        actionBar.setDisplayHomeAsUpEnabled(true);
//        setTitle("主板测试准备");
        setContentView(R.layout.activity_main);
        handler = new MyCheckHandler();
        scrollView = findViewById(R.id.scroll_view);
        textView = findViewById(R.id.textView);
        etFixture = findViewById(R.id.et_fixture);
        etUsername = findViewById(R.id.et_username);
        etPassword = findViewById(R.id.et_password);
        etFixture.setEnabled(false);
        etUsername.setEnabled(false);
        etPassword.setEnabled(false);
        readyToWork();
    }

    class MyCheckHandler extends Handler{
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            readyToWork();
        }
    }

    private void readyToWork(){
        if (!IS_PERMISSION_GRANTED){
            permissionCheck();
            return;
        }
        if (!IS_WIFI_CONNECTED){
            wifiConnectCheck();
            return;
        }
        if (!IS_BLUETOOTH_OPEN){
            bluetoothCheck();
            return;
        }
        if (!IS_CONFIG_LOADED){
            loadConfig();
            return;
        }
        if (!IS_CAN_LOGIN){
            waitForLogin();
//            return;
        }
        clearTestInfo();
        startActivity(new Intent(MainActivity.this, PcbaActivity.class));
    }

    private void permissionCheck(){
        appendLog("权限检查..");
        String[] permissions = new String[]{
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.CAMERA
        };
        //第三方权限动态获取框架
//        XXPermissions.with(this)
//                .permission(permissions)
//                .request(new OnPermissionCallback() {
//            @Override
//            public void onGranted(List<String> permissions, boolean all) {
//                if (all){
//                    IS_PERMISSION_GRANTED = true;
//                    appendLog("授权成功");
//                    handler.sendEmptyMessage(0);
//                }else{
//                    appendLogF("权限获取失败");
//                }
//            }
//        });
        //自定义权限获取方法
        checkPermissions(permissions, new PermissionCallback() {
            @Override
            public void onGranted() {
                IS_PERMISSION_GRANTED = true;
                appendLog("授权成功");
                handler.sendEmptyMessage(0);
            }

            @Override
            public void onFail() {
                appendLogF("权限获取失败");
            }
        });
    }

    private void wifiConnectCheck(){
        appendLog("检查wifi连接..");
        WifiUtil.getInstance(this).checkWifiConnection(WIFI_NAME, WIFI_PSWD, new CommonCallback() {
            @Override
            public void info(String info) {
                appendLog(info);
            }

            @Override
            public void onSuccess() {
                IS_WIFI_CONNECTED = true;
                handler.sendEmptyMessage(0);
            }

            @Override
            public void onFail(String error) {
                appendLogF(error);
            }
        });
    }

    private void bluetoothCheck(){
        BlueToothController controller = new BlueToothController();
        if (!controller.isSupportBlueTooth()) {
            appendLogF("未找到蓝牙模块,蓝牙检测失败");
            return;
        }
        appendLog("检查蓝牙是否打开..");
        if (!controller.getBlueToothStatus()){
            appendLog("蓝牙未开启，请手动打开");
            controller.turnOnBlueTooth(this, 100);
        }else{
            appendLog("蓝牙已开启");
            IS_BLUETOOTH_OPEN = true;
            handler.sendEmptyMessage(0);
        }
    }

    private void loadConfig(){
        try {
            appendLog("检查配置文件"+ GW.CONFIG_PCBA);
            GW.cfgPcba = GT.loadJsonFromFile(GW.CONFIG_PCBA);
            appendLog("加载成功");
            IS_CONFIG_LOADED = true;
            handler.sendEmptyMessage(0);
        } catch (Exception e) {
            e.printStackTrace();
            appendLogF("加载失败");
            showWarningDialog(e.getMessage());
//            finish();
        }
    }

    private void waitForLogin(){
        appendLog("等待操作员扫码开始..");
        etFixture.postDelayed(new Runnable() {
            @Override
            public void run() {
                etFixture.requestFocus();
            }
        }, 200);
        etFixture.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
                    //todo
                    canLogin("", "");
                    if (true) return true;

                    Log.d("etFixtureId", "回车键被按下");
                    String fixtureId = etFixture.getText().toString();
                    if (fixtureId.isEmpty()){
                        etFixture.setError("未输入治具ID");
                        return true;
                    }
                    GW.FIXTURE_ID = etFixture.getText().toString();
                    appendLog("治具ID: "+GW.FIXTURE_ID);
                    etFixture.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            etUsername.requestFocus();
                        }
                    }, 200);
                    return true;
                }
                return false;
            }
        });
        etUsername.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {

                    Log.d("etUsername", "回车键被按下");
                    String fixtureId = etUsername.getText().toString();
                    if (fixtureId.isEmpty()){
                        etUsername.setError("未输入用户名");
                        return true;
                    }
                    GW.OPERATOR_NAME = etUsername.getText().toString();
                    appendLog("用户名: "+ GW.OPERATOR_NAME);
                    etUsername.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            etPassword.requestFocus();
                        }
                    }, 200);
                    return true;
                }
                return false;
            }
        });
        etPassword.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
                    Log.d("etPassword", "回车键被按下");
                    String fixtureId = etPassword.getText().toString();
                    if (fixtureId.isEmpty()){
                        etPassword.setError("未输入密码");
                        return true;
                    }
                    GW.OPERATOR_PSWD = etPassword.getText().toString();
                    appendLog("密码: "+ GW.OPERATOR_PSWD);
                    canLogin(GW.OPERATOR_NAME, GW.OPERATOR_PSWD);
                    return true;
                }
                return false;
            }
        });
        etFixture.setEnabled(true);
        etUsername.setEnabled(true);
        etPassword.setEnabled(true);

    }

    private void canLogin(String operatorName, String operatorPswd) {
        appendLog("用户检查..");
        appendLog("检查通过");
        IS_CAN_LOGIN = true;
        handler.sendEmptyMessage(0);
    }

    private void clearTestInfo() {
        try (FileWriter writer = new FileWriter(Environment.getExternalStorageDirectory().getPath()+"/"+GW.LOGFILE_NAME, false)) {
            // 不需要写入任何内容，因为创建 FileWriter 时已经设置了 append 参数为 false
            // 如果 append 为 true，则会将新内容添加到文件的末尾，而不是清空文件

            // FileWriter 的构造函数：
            // FileWriter(File file) throws IOException
            // FileWriter(String fileName) throws IOException
            // FileWriter(File file, boolean append) throws IOException
            // FileWriter(String fileName, boolean append) throws IOException

            // 注意：第二个参数 append 如果为 true，则不会清空文件内容
            // 在这个例子中，我们传递 false 来确保文件内容被清空

            // 这里什么也不做，因为 FileWriter 已经在没有 append 的情况下创建，这会清空文件

            System.out.println("File content has been cleared.");
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("An error occurred while trying to clear the file.");
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100){
            bluetoothCheck();
        }
    }

    private void appendLog(final String content){
        XLog.d(content);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                textView.append(content+"\n");

            }
        });
        scrollView.postDelayed(new Runnable() {
            @Override
            public void run() {
                scrollView.fullScroll(ScrollView.FOCUS_DOWN);
            }
        }, 50);
    }

    private void appendLogF(final String content){
        XLog.d(content);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                textView.append(getSpanStr(content+"\n", Color.RED));

            }
        });
        scrollView.postDelayed(new Runnable() {
            @Override
            public void run() {
                scrollView.fullScroll(ScrollView.FOCUS_DOWN);
            }
        }, 50);
    }

    private SpannableString getSpanStr(String content, int color){
        SpannableString str = new SpannableString(content);
        str.setSpan(new ForegroundColorSpan(color), 0, str.length(),  Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return str;
    }
}